import React from "react";

interface ListItemProps {
	id: number;
	text: string;
	index: number;
	handleDrop: (draggedIndex: number, targetIndex: number) => void;
}

const ListItem: React.FC<ListItemProps> = ({ id, text, index, handleDrop }) => {
	const handleDragStart = (e: React.DragEvent<HTMLDivElement>) => {
		e.dataTransfer.setData("text/plain", index.toString());
	};

	const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
		e.preventDefault();
	};

	const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
		e.preventDefault();
	};

	const handleDropInternal = (e: React.DragEvent<HTMLDivElement>) => {
		const draggedIndex = +e.dataTransfer.getData("text/plain");
		if (draggedIndex !== index) {
			handleDrop(draggedIndex, index);
		}
	};

	return (
		<div
			draggable
			onDragStart={handleDragStart}
			onDragOver={handleDragOver}
			onDragEnter={handleDragEnter}
			onDrop={handleDropInternal}
			style={{ border: "1px solid #ccc", padding: "8px", marginBottom: "4px" }}>
			{text}
		</div>
	);
};

export default ListItem;
